package com.e2oto.seller.common.utils;

import android.app.Activity;
import android.view.Gravity;
import android.view.View;

import com.e2oto.seller.R;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;


/**
 * Created by ZhangLiQiang on 2017/9/20.
 */

public class PermissionUtils {

    private PermissionUtils() {
    }

    public static void requestPermissions(final Activity activity, final RequestPermissionCallback callback, String... manifestPermissions) {

        final RxPermissions rxPermission = new RxPermissions(activity);
        rxPermission.request(manifestPermissions)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        LogTools.e("请求权限结果:" + aBoolean);
                        if (aBoolean) {//全部allow
                            callback.allow();
                        } else {//部分allow 或者全部refuse
                            showPermissionRefuseDialog(activity);
                        }
                    }
                });

    }

    private static void showPermissionRefuseDialog(Activity activity) {
        DialogPlus.newDialog(activity).
                setContentHolder(new ViewHolder(R.layout.dialog_request_permission_result)).
                setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(DialogPlus dialog, View view) {
                        switch (view.getId()) {
                            case R.id.dialog_request_permission_sure_btn:
                                dialog.dismiss();
                                break;
                        }
                    }
                }).
                setGravity(Gravity.CENTER).
                create().
                show();

    }

    public interface RequestPermissionCallback {
        void allow();
    }

}
